// pages/mess/mess.js
var app=getApp();
Page({
  /**
   * 页面的初始数据
   */  
  data:{
    setWidthH:'',    
    nowQuest:"",
    answer1:"",
    answer2: "",
    answer3: "",
    answer4: "",
    nowQuesi:0,
    chanlinge:0,
    wordNumber:"一",//大写数字
    questions:[],
    nowQueses:{},
    haveAnswerI:0,//当前页面的题目索引
    quesTitle:["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"],
    utoux:"http://resource.jiyilive.com/img/ques/toux.png",
    uname:"当前用户",
    isGuoGK:"none",//过关框显示
    isWGuoGK: "none",//未过关框显示
    isQuesShow:"block",//问题框，提示出现的时候隐藏
    chanlinge:0,
    haveShare:0,
    allGk:3,//总关卡  
    haveGk: 0,   
    isHaveShare: false,//是否显示需要分享
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options){
    //console.log(options);
    var tcl = wx.getStorageSync("chanlinget" + app.globalData.selfActiveId),
      dtg = wx.getStorageSync("haveChanl" + app.globalData.selfActiveId),
      isS = wx.getStorageSync("haveShared" + app.globalData.selfActiveId);
      console.log(tcl, dtg, isS);
      
    //设置抽奖次数  
    this.setData({
      chanlinge: parseInt(tcl),//剩余闯关次数
      haveShare: parseInt(isS),//已经分享的次数
      haveGk: parseInt(dtg)//已经到达的关数
    });

    this.data.sys = wx.getSystemInfoSync();
    function makeFit(obj){//返回宽高差的一半，
      var tx = (obj.y - obj.x) / 2;
      var ty = (obj.y - obj.x) / 2;
      return { x: tx, y: ty }
    }
    var tr = makeFit({ x: this.data.sys.screenWidth, y: this.data.sys.screenHeight })
    this.setData({
      setWidthH: "width:" + this.data.sys.screenHeight + 'px;height:' + this.data.sys.screenWidth + "px;transform:rotate(90deg) translate(" + tr.y + "px," + tr.x + "px);-webkit-transform:rotate(90deg) translate(" + tr.y + "px," + tr.x + "px);"
    });    
   
    var _this=this;
    
    //请求问题数据     
    app.apiRequest({
      url: "/activityQa/queryOne",
      data: { "id": app.globalData.selfActiveId},
      success: function(res){
        console.log("所有问题：",res);
        var datas = [makearr(res.data.data)]
        function makearr(ar){
           ar.answers=ar.answers.split("$&");
           ar.title=ar.tile;
          // ar.answer = ar.answer
          return ar;
          for(var i=0;i<ar.length;i++){
            var tstr=ar[i].answers.replace(/[\[\]]/g,'');
            ar[i].answers=tstr.split(",");
          }
          return ar;
        }
        _this.setData({
          questions: datas
        });
        _this.makeQues();
      }
    });
    /*
    //单独添加，//临时模拟不需要ajax获取数据，，，正式的逻辑在上边注释着。这之后的逻辑正常
    this.setData({
      questions: this.data.questionsd
    })
    this.makeQues();
    */   
  //设置头像
  var info=app.globalData.userInfo;
    if(info!==null && JSON.stringify(info)!=="{}"){
      this.setData({
        uname:info.nickName,
        utoux: info.avatarUrl
      });
    }
  
  },  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function(){
  },
  makeQues:function(){
    var obj = this.data.questions[0];
    // console.log(obj);return;
    this.setData({
      nowQueses:obj,
      nowQuest: obj.title,
      answer1:obj.answers[0]+'',
      answer2:obj.answers[1]+'',
      answer3:obj.answers[2]+'',
      answer4:obj.answers[3]+'',
      wordNumber: this.data.quesTitle[this.data.nowQuesi]
    });
    
    // this.data.nowQuesi += 1;
    // if(this.data.questions.length==0){//没问题了，赶紧再请求
    //   this.data.questions = this.data.questionsd;
      
    // }
  },
  checkChanl:function(call){//检测是否还能继续
    var tcl = this.data.chanlinge;       
    // console.log("还剩余的挑战次数：", tcl)    
    tcl += ''
    wx.setStorageSync("chanlinget" + app.globalData.selfActiveId, tcl);    
    if (tcl <= 0) {
      if (this.data.haveShare > 0) {
        this.showGoShare();
        return;
      }
      wx.showToast({ "title": "您的答题次数用光了，请明天再来吧", "icon": "none" });
      setTimeout(() => {
        this.backhomep();
      }, 1000);
      return;
    }
    
    call();//都检测没问题，继续下一关
  },
  nextChanl:function(){//下一关    
    this.setData({
      isGuoGK: "none",
      isQuesShow: "block"
    });
    this.data.chanlinge--
    var tcl=this.data.chanlinge;
    tcl+=""
    wx.setStorageSync("chanlinget" + app.globalData.selfActiveId, tcl); 
    this.checkChanl(this.makeNext)
  },
  reChanlege: function () {//重新挑战
    // this.data.nowQuesi = 0;        
    this.setData({
      isWGuoGK: "none",
      isQuesShow: "block"
    });
    this.setData({
      chanlinge: this.data.chanlinge-1
    });
    this.checkChanl(function () { });
  },
  checkQues:function(e){
    var ind=e.target.dataset.set;    
    if (ind == this.data.nowQueses.answer){
      this.setData({
        haveGk: this.data.haveGk + 1
      })
      var dtg=this.data.haveGk+"";
      wx.setStorageSync("haveChanl" + app.globalData.selfActiveId,dtg);
      // console.log("关卡情况", this.data.haveGk, this.data.allGk)
      //先检验是不是通关了
      var _this=this;
      if (this.data.haveGk >= this.data.allGk) {
        app.apiRequest({
          url: "/activityUser/update",
          data: {
            "activityId": app.globalData.selfActiveId, "passQty": 12
          },
          success: function (res) {            
            //过关
            wx.showToast({//layer.msg类的提示框，自动隐藏
              title: "恭喜通关",
              icon: "success"
            });
            setTimeout(function(){
              _this.backhomep();
            },1000);
          }
        });
        return;
      }
      //显示过关成功
      setTimeout(() => {//正确
        this.setData({
          isGuoGK: "block",
          isQuesShow: "none"
        });
      }, 100);
      return      
    }else{
      setTimeout(()=>{//错误
        this.setData({
          isWGuoGK:"block",
          isQuesShow:"none"
        });
      },100);
    }
  },  
  backhomep:function(){
    //this.reChanlege();
    wx.redirectTo({ url:"../index/index?id="+app.globalData.selfActiveId});
  },
  backhomed: function () {
    wx.showModal({
      title: "退出任务",
      content: "退出任务将返回活动首页，此操作不消耗次数。您确定要退出任务么？",
      success: function (e) {
        if (e.confirm) {
          wx.navigateTo({ url: "../index/index?id=" + app.globalData.selfActiveId });
        } else if (e.cancel) { }
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (){
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  //  wx.showToast({title:"触底啦~"});
    //console.log("触底啦")
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {//设置分享内容
    var user = wx.getStorageSync('user');

    var userid = app.globalData.userNumId;
    var url = "/pages/index/index?userId=" + userid + "&shareId=" + app.globalData.selfActiveId
    //console.log(escape(url))
    //url=escape(url)
    return {
      title: "快来助力，为我idol加油，一起拿票看演出！",
      path: url,
      imageUrl: "http://resource.jiyilive.com/img/index/share1.jpg",
      success: function (res) {        
        var shareTicket = res.shareTickets[0] || '';
        wx.getShareInfo({
          shareTicket: shareTicket,
          success: function (res) {
            console.log(res);
            wx.showModel({
              title: "text",
              text: JSON.stringify(res)
            });
          }
        });
      }
    }
  },
  haveShared: function () {//已经分享     
    this.data.haveShare-=1;
    var tsS=this.data.haveShare+""
    wx.setStorageSync("haveShared" + app.globalData.selfActiveId,tsS);
    wx.setStorageSync("chanlinget" + app.globalData.selfActiveId,'1');
    this.data.chanlinge=1;
    wx.showLoading()
    //选择下一关
    setTimeout(function(){
      wx.hideLoading();
      this.setData({ isHaveShare: false });
      wx.showToast({ "title": "闯关次数+1,进入下一关", "icon": "none" })
      setTimeout(() => { this.makeNext(); }, 1000);
    }.bind(this),4000);    
  },
  makeNext: function () {
    var tround = Math.random() > 0.5;
    if (tround) {
      wx.redirectTo({ url: "../mess/mess" })
      return;
     //直接进入下一题
      this.data.questions.shift()
      this.makeQues();
    } else {
      wx.redirectTo({ url: "../pict/pict" })
    }
  },
  showGoShare: function () {//显示需要分享获得次数窗口；
    this.setData({ isHaveShare: true });
  }
})